#!/usr/bin/env ruby
require 'eventmachine'
require 'logger'
require File.expand_path("../blue.rb", __FILE__)

TIMER = 5

host = "0.0.0.0"
port = (ARGV[0].to_i > 0) ? ARGV[0].to_i : 12345

$logger = Logger.new(STDOUT)

module ScoreboardServer
	def initialize(scoreboard)
		@peer = Socket.unpack_sockaddr_in(get_peername)
		@team = @peer[1].split(".")[2].to_i
		@peer = @peer.reverse.join(":")
		$logger.info("#{@peer} connected")
		hello()
		@buf = ""
		@scoreboard = scoreboard
        refresh()
	end

	def unbind()
		$logger.info("#{@peer} disconnected")
	end

	def receive_data(data)
		begin
			EventMachine::PeriodicTimer.new(TIMER) do
			refresh()
			end
		rescue Exception =>e
			puts "timeout"
		end
	end

	def refresh()
		send(@scoreboard.update())
		#fill = @scoreboard.width()
		str = "Auto-update: #{TIMER} seconds"
		#fill -= str.length
		send((" "*10) + str)
	end

	def send(data)
		send_data(data + "\n")
	end

	def hello()
		send("Welcome to the BCTF hacking star Scoreboard")
	end
end

EventMachine::run do
	scoreboard = Scoreboard.new()
	EventMachine::PeriodicTimer.new(TIMER) { scoreboard.update() }
	EventMachine::start_server(host, port, ScoreboardServer, scoreboard)
	$logger.info("Listening on #{host}:#{port}")
end
